package com.twh.www.controller;

import com.twh.www.entity.WnCart;
import com.twh.www.entity.WnGoods;
import com.twh.www.entity.WnUser;
import com.twh.www.service.WnCartService;
import com.twh.www.service.WnGoodsService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private WnCartService cartService;

    @Autowired
    private WnGoodsService goodsService;

    @RequestMapping("/add")
    @ResponseBody
    public String addToCart(@RequestParam Integer goodsId, @RequestParam Integer num, HttpSession session) {
        WnUser user = (WnUser) session.getAttribute("LoginUser");
        if (user == null) return "fail:user";
        return cartService.addToCart(user.getId(), goodsId, num);
    }

    @RequestMapping("/list")
    public String cartList(Model model, HttpSession session) {
        WnUser user = (WnUser) session.getAttribute("LoginUser");
        if (user == null) return "redirect:/user/login";
        List<WnCart> carItems = cartService.getCartByUserId(user.getId());
        model.addAttribute("carItems", carItems);
        model.addAttribute("totalPrice", cartService.getCartTotalPrice(user.getId()));
        return "cart";
    }

    @RequestMapping("/update")
    @ResponseBody
    public String updateCart(@RequestParam Integer cartId, @RequestParam Integer num) {
        WnCart cart = cartService.getById(cartId);
        if (cart == null) return "notfound";
        WnGoods goods = goodsService.getById(cart.getGoodsId());
        if (goods == null) return "nogoods";
        if (goods.getStock() < num) return "outofstock";
        boolean result = cartService.updateCartNum(cartId, num);
        return result ? "success" : "fail";
    }

    @RequestMapping("/remove")
    @ResponseBody
    public String removeCart(@RequestParam Integer cartId) {
        boolean result = cartService.removeCartItem(cartId);
        return result ? "success" : "fail";
    }
}
